import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    // 默认重定向到登录页面
    {
      path: '/',
      redirect: '/login'
    },
    // 登录页（无布局）
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/user/Login')
    },

    // 用户端路由（带布局）
    {
      path: '/user',
      component: () => import('@/layouts/UserLayout'),
      children: [
        {
          path: 'home',
          name: 'Home',
          component: () => import('@/views/user/Home')
        },
        {
          path: 'pet-list',
          name: 'PetList',
          component: () => import('@/views/user/PetList')
        },
        {
          path: 'pet-detail',
          name: 'PetDetail',
          component: () => import('@/views/user/PetDetail')
        },
        {
          path: 'shop',
          name: 'Shop',
          component: () => import('@/views/user/Shop')
        },
        {
          path: 'product-detail',
          name: 'ProductDetail',
          component: () => import('@/views/user/ProductDetail')
        },
        {
          path: 'service-reserve',
          name: 'ServiceReserve',
          component: () => import('@/views/user/ServiceReserve')
        },
        {
          path: 'foster-reserve',
          name: 'FosterReserve',
          component: () => import('@/views/user/FosterReserve')
        },
        {
          path: 'pet-health',
          name: 'PetHealth',
          component: () => import('@/views/user/PetHealth')
        },
        {
          path: 'user-center',
          name: 'UserCenter',
          component: () => import('@/views/user/UserCenter')
        }
      ]
    },

    // 注册页（无布局）
    {
      path: '/register',
      name: 'Register',
      component: () => import('@/views/user/Register')
    },

    // 管理端路由（带布局）
    {
      path: '/admin',
      component: () => import('@/layouts/AdminLayout'),
      redirect: '/admin/dashboard',
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('@/views/admin/Dashboard')
        },
        {
          path: 'pet-manage',
          name: 'PetManage',
          component: () => import('@/views/admin/PetManage')
        },
        {
          path: 'pet-care-manage',
          name: 'PetCareManage',
          component: () => import('@/views/admin/PetCareManage')
        },
        {
          path: 'health-manage',
          name: 'HealthManage',
          component: () => import('@/views/admin/HealthManage')
        },
        {
          path: 'sale-pet-manage',
          name: 'SalePetManage',
          component: () => import('@/views/admin/SalePetManage')
        },
        {
          path: 'staff-manage',
          name: 'StaffManage',
          component: () => import('@/views/admin/StaffManage')
        },
        {
          path: 'service-manage',
          name: 'ServiceManage',
          component: () => import('@/views/admin/ServiceManage')
        },
        {
          path: 'foster-manage',
          name: 'FosterManage',
          component: () => import('@/views/admin/FosterManage')
        },
        {
          path: 'order-manage',
          name: 'OrderManage',
          component: () => import('@/views/admin/OrderManage')
        },
        {
          path: 'system-setting',
          name: 'SystemSetting',
          component: () => import('@/views/admin/SystemSetting')
        },
        {
          path: 'auth-manage',
          name: 'AuthManage',
          component: () => import('@/views/admin/AuthManage')
        }
      ]
    },

    // 404 页面
    {
      path: '*',
      redirect: '/'
    }
  ]
})

// 路由守卫：检查登录状态
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const userInfoStr = localStorage.getItem('userInfo')
  
  // 如果访问登录页或注册页
  if (to.path === '/login' || to.path === '/register') {
    // 如果已登录，根据用户类型跳转到对应首页
    if (token && userInfoStr) {
      try {
        const user = JSON.parse(userInfoStr)
        // 判断用户类型，跳转到对应首页
        const isAdmin = user.userType === 2 || 
                       user.role === 'ROLE_ADMIN' || 
                       user.role === 'admin' || 
                       user.username === 'admin'
        
        if (isAdmin) {
          next('/admin/dashboard')
        } else {
          next('/user/home')
        }
      } catch (e) {
        // 解析失败，允许访问登录页
        next()
      }
    } else {
      // 未登录，允许访问登录页
      next()
    }
  } 
  // 访问管理端页面，需要管理员权限
  else if (to.path.startsWith('/admin')) {
    if (!token || !userInfoStr) {
      // 未登录，跳转到登录页
      next('/login')
    } else {
      try {
        const user = JSON.parse(userInfoStr)
        // 检查是否为管理员
        const isAdmin = user.userType === 2 || 
                       user.role === 'ROLE_ADMIN' || 
                       user.role === 'admin' || 
                       user.username === 'admin'
        
        if (isAdmin) {
          // 是管理员，允许访问
          next()
        } else {
          // 不是管理员，跳转到用户首页
          next('/user/home')
        }
      } catch (e) {
        // 解析失败，跳转到登录页
        next('/login')
      }
    }
  }
  // 访问用户端页面，需要登录
  else if (to.path.startsWith('/user')) {
    if (!token || !userInfoStr) {
      // 未登录，跳转到登录页
      next('/login')
    } else {
      // 已登录，允许访问
      next()
    }
  }
  else {
    // 其他页面，允许访问
    next()
  }
})

export default router
